﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Command;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.DAL;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Event;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Models;

namespace WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Handler
{
    // 订单处理程序（负责创建订单并管理事务）
    public class OrderCommandHandler : IRequestHandler<CreateOrderCommand, OrderResult>
    {
        private readonly AppDbContext _dbContext;
        private readonly IMediator _mediator;

        public OrderCommandHandler(AppDbContext dbContext, IMediator mediator)
        {
            _dbContext = dbContext;
            _mediator = mediator;
        }

        public async Task<OrderResult> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
        {
            // 1. 检查产品是否存在及库存是否充足
            var product = await _dbContext.Products
                .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);

            if (product == null)
            {
                return new OrderResult { Success = false, Message = "产品不存在" };
            }

            if (product.StockQuantity < request.Quantity)
            {
                return new OrderResult
                {
                    Success = false,
                    Message = $"库存不足，当前库存: {product.StockQuantity}"
                };
            }

            // 2. 开启数据库事务（关键：所有操作在同一事务中）
            using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);

            try
            {
                // 3. 创建订单
                var order = new Order
                {
                    ProductId = request.ProductId,
                    Quantity = request.Quantity,
                    OrderDate = DateTime.UtcNow,
                    Status = "Created"
                };

                _dbContext.Orders.Add(order);
                await _dbContext.SaveChangesAsync(cancellationToken);

                // 4. 发布事件（通知库存和物流服务处理，在同一事务中）
                await _mediator.Publish(new OrderCreatedEvent
                {
                    OrderId = order.Id,
                    ProductId = request.ProductId,
                    Quantity = request.Quantity
                }, cancellationToken);

                // 5. 所有操作成功，提交事务
                await transaction.CommitAsync(cancellationToken);

                return new OrderResult
                {
                    Success = true,
                    Message = "订单创建成功",
                    OrderId = order.Id
                };
            }
            catch (Exception ex)
            {
                // 6. 任何操作失败，回滚事务
                await transaction.RollbackAsync(cancellationToken);
                return new OrderResult
                {
                    Success = false,
                    Message = $"操作失败: {ex.Message}"
                };
            }
        }
    }
}
